package com.example.FileSearch;

import java.io.File;

/**
 * Created by fany on 14-1-22.
 */
public class FileSearcher {
    public FileSearcher(IFileRecorder recorder){
        _recorder = recorder;
    }

    public void LoadFiles(String root){
        LoadFiles(root, false);
    }

    public void LoadFiles(String root, boolean forceReload){
        if(NeedReloadFileList() || forceReload){
            try {
                File file = new File(root);
                _recorder.Clear();
                DoSearchFiles(file);
            } catch (IllegalArgumentException ex){

            }
        }
    }

    public String [] Search(String filter){
        return _recorder.SearchFile(filter);
    }

    private void DoSearchFiles(File baseFile) {
        File[] childFiles = baseFile.listFiles();
        if(childFiles == null){
            return;
        }
        for (File file : childFiles) {
            _recorder.Record(file.getAbsolutePath());
            if (file.isDirectory()) {
                DoSearchFiles(file);
            }
        }
    }

    private boolean NeedReloadFileList(){
        return !_recorder.HasLoaded();
    }

    private IFileRecorder _recorder;
}